<template lang="pug">
  .page.h-100
    .clearfix
      .search-form.mb-10.pl-10.pr-10(v-if="hasGetFinanceInvoiceList")
        Form.ivu-row.ivu-form-basic(ref="formData" :model="formData" :rules="rules" :label-width="90")
          FormItem.form-item.ivu-col.pr-20.mb-15(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'select'")
              Select(v-if="item.fn" v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable @on-change="listenCall(item.fn, item.model, $event)")
                Option(
                  v-for="(c_item, index) in arrListDown[item.options]"
                  :value="c_item.value"
                  :key="index"
                ) {{ c_item.label }}
              Select(v-else v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable)
                Option(
                  v-for="(c_item, index) in arrListDown[item.options]"
                  :value="c_item.value"
                  :key="index"
                ) {{ c_item.label }}
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder" clearable)
            template(v-if="item.type === 'radio'")
              RadioGroup(type="button" v-model="formData[item.model]")
                Radio.display-inline-block(v-for="c_item of item.radioArr" :label="c_item.value") {{c_item.label}}
            template(v-if="item.type === 'intervalM'")
              DatePicker.pull-left.interval-date(v-model="formData[item.model1]" :placeholder="item.placeholder1" type="month" @on-change="(val, type) => handleChangeDatePicker(val, item.model1)")
              span.pl-10.pr-10.pull-left.line-h-32 --
              DatePicker.pull-left.interval-date(v-model="formData[item.model2]" :placeholder="item.placeholder2" type="month" @on-change="(val, type) => handleChangeDatePicker(val, item.model2)")
            template(v-if="item.type === 'intervalMoney'")
              Input.pull-left.w120(v-model="formData[item.model1]" :placeholder="item.placeholder1" clearable)
              span.pl-10.pr-10.pull-left.line-h-32 --
              Input.pull-left.w120(v-model="formData[item.model2]" :placeholder="item.placeholder2" clearable)
            template(v-if="item.type === 'button'")
              Button(type="info" @click="searchFn") 查询

      .pl-20.pr-20.bg-white
        Table.hasTitle-table.beautiful-table(:columns="thead" :data="tableData" :stripe="true" ref="demoTable" @on-selection-change="handleOnSelectChange")
          .clearfix.font-16(slot="header")
            .table-title-lefttxt.pull-left
              |合计
              span.text-info.pl-5.pr-5.font-weight {{tableComone.totalRows}}
              |条
            .pull-right.table-title-btns
              //- Button.mr-10(v-if="hasAddFinanceInvoice" type="error" @click="handleShowInvoiceInstantModal('createModal', null)") 即时开票
              //- Button.mr-10(v-if="hasAddFinanceInvoice" type="info" @click="handleShowInvoiceApplyModal('createModal', null)") 开票申请
              //- Button.mr-10(v-if="hasReturn" type="info" @click="isDeleteModal" :disabled="!selectedArr.length > 0") 撤回
              Button.mr-10(v-if="hasExportInvoice" type="info" @click="exportInvoice") 导出
              Button(v-if="hasExportInvoice" type="info" @click="exportList") 导出明细
              
          .clearfix.pl-20.pr-20(slot="footer")
            Page(
              :total="tableComone.totalRows"
              @on-change="onChangePage"
              @on-page-size-change="onpageSizeChange"
              show-sizer
              show-total
              placement="top"
              prev-text="上一页"
              next-text="下一页"
              :page-size-opts="[10, 20, 30, 50, 100]"
            )
          template(slot-scope="{ row, index }" slot="action")
            //- Button.mr-10(v-if="hasReplaceFinanceInvoice && row.invoiceChannel == 0" type="text" size="small" @click="handleShowInvoiceApplyModal('replaceModal', row.invoiceID)") 退换票申请
            //- Button.mr-10(v-if="hasApplyBackInvoice && row.invoiceChannel == 0" type="text" size="small" @click="handleShowInvoiceApplyModal('replaceModal', row.invoiceID, row)") 退票申请
            
            Button.mr-10(v-if="hasInvoiceInfo && row.invoiceChannel != 1" type="text" size="small" @click="handleShowInvoiceApplyModal('lookModal', row.invoiceID)") 发票信息
            //- Button.mr-10(v-if="hasEdit && row.invoiceChannel != 1" type="text" size="small" @click="handleShowInvoiceApplyModal('editModal', row.invoiceID)" :disabled="['已撤回', '已驳回'].indexOf(row.statusRemark) == -1") 编辑
            
            //- Button.mr-10(v-if="hasReplaceFinanceInvoice && row.invoiceChannel == 1" type="text" size="small" @click="handleShowInvoiceInstantModal('replaceModal', row.invoiceID)") 退换票申请
            //- Button.mr-10(v-if="hasApplyBackInvoice && row.invoiceChannel == 1" type="text" size="small" @click="handleShowInvoiceInstantModal('replaceModal', row.invoiceID, row)") 退票申请
            Button.mr-10(v-if="hasInvoiceInfo && row.invoiceChannel == 1" type="text" size="small" @click="handleShowInvoiceInstantModal('lookModal', row.invoiceID)") 发票信息
            //- Button.mr-10(v-if="hasEdit && row.invoiceChannel == 1" type="text" size="small" @click="handleShowInvoiceInstantModal('editModal', row.invoiceID)" :disabled="['已撤回', '已驳回'].indexOf(row.statusRemark) == -1") 编辑
            //- Button(type="text" size="small" @click="gotoReceivableBillsList(row)") 应收账单
            //- Dropdown.pull-right.pt-15.has-button-dropdown(placement="bottom-end")
            //-   a(href="javascript:void(0)")
            //-     Icon.text-info.font-24(type="md-more")
            //-   DropdownMenu(slot="list")
            //-     DropdownItem(v-if="hasCreate")
            //-       Button(type="text" size="small" @click="gotoReceivableBillsList(row)") 应收账单
             
    //- 开票申请弹窗
    InvoiceApplyModal(ref="InvoiceApplyModal" @query="searchFn")

    //- 即时开票弹窗
    InvoiceInstantModal(ref="InvoiceInstantModal" @query="searchFn")

    //- 退票
    ReplaceModal(ref="ReplaceModal" @query="searchFn")
    
</template>

<script>
import { Common } from '@/utils/common.js'
import { FinanceApi } from '@/api/Finance.api.js'
import { FinanceInvoiceApi } from '@/api/FinanceInvoice.api.js'
import { InvoiceManageThead } from './tableHead.js'
import _cloneDeep from 'clone-deep'
import InvoiceApplyModal from './modal/InvoiceApplyModal.vue'
import InvoiceInstantModal from './modal/InvoiceInstantModal.vue'
import ReplaceModal from './modal/ReplaceModal.vue'
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro.replace('/api', '/')

export default {
  // name: 'invoiceApply', // 发票申请页面

  components: {
    InvoiceApplyModal,
    InvoiceInstantModal,
    ReplaceModal
  },

  computed: {
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 查询
    hasGetFinanceInvoiceList () {
      return this.actionArr.indexOf('GetFinanceInvoiceList') > -1
    },
    // 导出
    hasExportInvoice () {
      return this.actionArr.indexOf('ExportInvoice') > -1
    },
    // 退换票申请
    hasReplaceFinanceInvoice () {
      return this.actionArr.indexOf('ReplaceFinanceInvoice') > -1
    },
    // 退票申请
    hasApplyBackInvoice () {
      return this.actionArr.indexOf('ApplyBackInvoice') > -1
    },
    // 编辑
    hasEdit () {
      return this.actionArr.indexOf('Edit') > -1
    },
    // 撤回
    hasReturn () {
      return this.actionArr.indexOf('Return') > -1
    },
    // 发票信息
    hasInvoiceInfo () {
      return this.actionArr.indexOf('InvoiceInfo') > -1
    },
    // 开票申请
    hasAddFinanceInvoice () {
      return this.actionArr.indexOf('AddFinanceInvoice') > -1
    }
  },

  data () {
    return {
      thead: _cloneDeep(InvoiceManageThead),
      tableData: [],
      selectedId: [], // 勾选的id集合,array格式
      selectedArr: [], // 勾选的id, name数组集合
      tableComone: {
        pageIndex: 1,
        totalRows: 0,
        pageSize: 10
      },
      formData: {
        isApply: true,
        parentName: '',
        companyName: '',
        status: '',
        startDate: null,
        endDate: null,
        startAmt: '',
        endAmt: '',
      },
      formItem: [
        // { type: 'input', label: '集团公司：', placeholder: '请输入集团公司', prop: 'parentName', model: 'parentName', style: 'ivu-col-span-8' },
        // { type: 'input', label: '客户名称：', placeholder: '请输入客户名称', prop: 'companyName', model: 'companyName', style: 'ivu-col-span-8' },
        { type: 'select', label: '开票状态：', placeholder: '请选择开票状态', prop: 'status', model: 'status', style: 'ivu-col-span-8', options: 'status' },
        { type: 'intervalM', label: '费用月份：', placeholder1: '开始日期', prop1: 'startDate', model1: 'startDate', placeholder2: '结束日期', prop2: 'endDate', model2: 'endDate', style: 'ivu-col-span-8' },
        // { type: 'intervalMoney', label: '开票金额：', placeholder1: '起始金额', prop1: 'startAmt', model1: 'startAmt', placeholder2: '结束金额', prop2: 'endAmt', model2: 'endAmt', style: 'ivu-col-span-8' },
        { type: 'button', style: 'ivu-col-span-8' }
      ],
      arrListDown: {
        parentCompanys: [],
        childrenCompanys: [],
        status: []
      },
      rules: {}
    }
  },

  mounted () {
    this.getEnum()
    this.getParentCompanys()
    this.query()

    console.log('❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀ this.$route.query: ', this.$route.query)

    // 从客户账单过来，显示开票申请弹窗
    // if (this.$route.query.isFromCustomerBill) {
    //   console.log('xxxxxxxxxxxxx 从客户账单过来，显示开票申请弹窗 xxxxxxxxxxxxxxx')
    //   setTimeout(() => {
    //     this.handleShowInvoiceApplyModal('createModal', null)
    //   }, 1000);
    // }
  },

  methods: {
    // 监听所有调用的方法
    listenCall (methodsWords, ...values) {
      this[methodsWords](...values)
    },

    // 数据字典
    getEnum () {
      let groupName = 'financeinvoice.status'
      Common.getEnum(groupName, this.arrListDown)
    },

    // 数据字典-获取集团公司
    getParentCompanys () {
      Common.getParentCompanys(this.arrListDown, 'parentCompanys')
    },
 
    // 搜索
    searchFn () {
      this.tableComone.pageIndex = 1
      this.query()
    },

    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage (val) {
      this.tableComone.pageIndex = val
      this.query()
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange (val) {
      this.tableComone.pageIndex = 1
      this.tableComone.pageSize = val
      this.query()
    },
    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query () {
      this.selectedId = []
      this.selectedArr = []
      var params = {
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize,
      }
      let res = await FinanceInvoiceApi.getFinanceInvoiceList({...params, ...this.formData})
      console.log('获取列表res: ', res)
      if (res.status === 200 && res.data.success) {
        this.tableData = res.data.data
        this.tableComone.totalRows = res.data.totalRows
      } else {
        this.tableData = []
      }
    },

    // 表格选择操作
    handleOnSelectChange (value) {
      this.selectedArr = value.map((item) => {
        return { id: item.invoiceID, parentID: item.parentID, parentName: item.parentName }
      })
      this.selectedId = value.map((item) => {
        return item.invoiceID
      })
      console.log('列表勾选数组1', this.selectedArr)
      console.log('列表勾选数组2', this.selectedId)
    },

    // 显示开票申请弹窗
    handleShowInvoiceApplyModal (modalKey, id, row) {
      this.$refs.InvoiceApplyModal.modalKey = modalKey
      switch(modalKey){
        case 'createModal' :
          this.$refs.InvoiceApplyModal.createInvoiceModalTitle = '新建发票申请'
          break;
        case 'editModal' :
          this.$refs.InvoiceApplyModal.createInvoiceModalTitle = '编辑发票申请'
          break;
        case 'lookModal' :
          this.$refs.InvoiceApplyModal.createInvoiceModalTitle = '查看发票信息'
          break;
        case 'replaceModal' :
          this.$refs.ReplaceModal.replaceModalModalTitle = '退票申请'
          break;
      }
      if (modalKey == 'replaceModal') {
        if (row.status != 3) {
          this.$Message.error("非已开票的发票，无法退换票")
          return
        }
        let year = new Date().getFullYear()
        let month = new Date().getMonth() + 1
        this.$refs.ReplaceModal.isThisMonth = year == row.periodYear && month == row.periodMonth
        this.$refs.ReplaceModal.formData.invoiceID = id
        this.$refs.ReplaceModal.show()
      } else {
        if (id) {
          this.$refs.InvoiceApplyModal.getModel(id)
        } else {
          this.$refs.InvoiceApplyModal.show(id)
        }
        this.$refs.InvoiceApplyModal.arrListDown.parentCompanys = this.arrListDown.parentCompanys
        this.$refs.InvoiceApplyModal.arrListDown.status = this.arrListDown.status
      }
    },

    // 显示即时开票弹窗
    handleShowInvoiceInstantModal (modalKey, id, row) {
      this.$refs.InvoiceInstantModal.modalKey = modalKey
      switch(modalKey){
        case 'createModal' :
          this.$refs.InvoiceInstantModal.createInvoiceModalTitle = '新建发票申请(即时)'
          break;
        case 'editModal' :
          this.$refs.InvoiceInstantModal.createInvoiceModalTitle = '编辑发票申请(即时)'
          break;
        case 'lookModal' :
          this.$refs.InvoiceInstantModal.createInvoiceModalTitle = '查看发票信息(即时)'
          break;
        case 'replaceModal' :
          this.$refs.ReplaceModal.replaceModalModalTitle = '退票申请(即时)'
          break;
      }
      if (modalKey == 'replaceModal') {
        if (row.status != 3) {
          this.$Message.error("非已开票的发票，无法退换票")
          return
        }
        let year = new Date().getFullYear()
        let month = new Date().getMonth() + 1
        let _year = new Date(row.doTime).getFullYear()
        let _month = new Date(row.doTime).getMonth() + 1
        this.$refs.ReplaceModal.isThisMonth = year == _year && month == row._month
        this.$refs.ReplaceModal.formData.invoiceID = id
        this.$refs.ReplaceModal.show()
      } else {
        if (id) {
          this.$refs.InvoiceInstantModal.getModel(id)
        } else {
          this.$refs.InvoiceInstantModal.show()
        }
        // this.$refs.InvoiceInstantModal.arrListDown.parentCompanys = this.arrListDown.parentCompanys
        this.$refs.InvoiceInstantModal.arrListDown.status = this.arrListDown.status
      }
    },

    // 获取所有集团下的公司
    parentCompanysChange (model, event) {
      if (event) {
        FinanceApi.getAllChildCompanys({companyGuid: event}).then(resp => {
          console.log('获取所有集团下的公司: ', resp)
          var arr = []
          if (resp.status === 200) {
            var costomer = resp.data.find(item => {return item.group == 'customer'})
            console.log('costomer: ', costomer)
            costomer.items.map(item => {arr.push({label: item.value, value: item.key})})
            this.arrListDown.childrenCompanys = arr
          }
        })
      }
    },

    // 是否撤回前询问
    isDeleteModal () {
      this.$Modal.confirm({
        title: '确认是否撤回该条信息',
        onOk: () => {
          this.changeFinanceInvoice()
        }
      })
    },

    // 确认撤回
    async changeFinanceInvoice () {
      var params = {
        Invoices: this.selectedId,
        Status: -1
      }
      let res = await FinanceInvoiceApi.changeFinanceInvoice(params)
      if (res.status === 200 && res.data.success) {
        this.$Message.success(res.data.message)
        this.query()
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 导出发票申请
    async exportInvoice () {
      FinanceInvoiceApi.exportInvoice({...this.formData, ids: this.selectedId.join(',')}).then(resp => {
        console.log('导出发票申请resp: ', resp)
        if (resp.status == 200 && resp.data.success) {
          console.log('❤ 返回链接: ', baseUrl + resp.data.message)
          window.open(baseUrl + resp.data.message, '_blank')
        } else {
          this.$Message.error(resp.data.message)
        }
      })
    },

    // 批量导出
    async exportList () {
      FinanceInvoiceApi.export({...this.formData, ids: this.selectedId.join(',')}).then(resp => {
        console.log('批量导出发票申请resp: ', resp)
        if (resp.status == 200 && resp.data.success) {
          console.log('返回链接: ', baseUrl + resp.data.message)
          window.open(baseUrl + resp.data.message, '_blank')
        } else {
          this.$Message.error(resp.data.message)
        }
      })
    },

    // 日期选择
    handleChangeDatePicker (val, model) {
      this.formData[model] = val
    },

    // 去往应收账单
    gotoReceivableBillsList (row) {
      var month = row.periodMonth < 10 ? '0' + row.periodMonth : row.periodMonth
      this.$router.push({
        path: '/receivableBillsList',
        name: 'receivableBillsList',
        query: {
          serverName: row.serverName,
          companyName: row.companyName,
          date: row.periodYear + '-' + month
        }
      })
    },
  } // methods end
}
</script>

<style lang="less" scoped>

</style>
